package top.hencter.weibo.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.util.ArrayList;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import top.hencter.weibo.R;
import top.hencter.weibo.adapter.IndexListAdapter;
import top.hencter.weibo.bean.IndexItem;

public class SearchResultActivity extends AppCompatActivity {

    ListView listView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_result);

        listView = findViewById(R.id.hot_search_list_view);

        // 获取 FindFragment 传来的搜索关键字
        Intent intent = getIntent();
        String keyWords = intent.getStringExtra("keyWords");
        System.out.println(keyWords);

        // 获取热搜数据
        getHotSearchResult(keyWords);


    }

    public void getHotSearchResult(String key_words) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("http://129.28.159.96:7001/v1/test/search?key=" + key_words)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.i("======", e.toString());
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String data = response.body().string();
                Log.i("======", data);
                Gson gson = new Gson();
                final ArrayList<IndexItem> mainItems;
                mainItems = gson.fromJson(data, new TypeToken<ArrayList<IndexItem>>() {
                }.getType());
                SearchResultActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (data.equals("[]")) {
                            Toast.makeText(SearchResultActivity.this, "没有符合条件的结果", Toast.LENGTH_LONG).show();
                        } else {
                            // 这里沿用之前首页制作的来展示
                            IndexListAdapter mainListAdapter = new IndexListAdapter(SearchResultActivity.this, R.layout.index_list_item, mainItems);
                            listView.setAdapter(mainListAdapter);
                        }
                    }
                });


            }
        });
    }


}